package com.test;

import java.io.IOException;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

@SuppressWarnings("unchecked")
public class ReadXML4JDOM {

	public static void main(String[] args) {
		read("myschool.xml");
		System.out.println("执行完毕！");
	}

	@SuppressWarnings("rawtypes")
	public static void read(String filename) {
		SAXBuilder saxb = new SAXBuilder();
		try {
			Document dc = saxb.build(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename));
			Element root = dc.getRootElement();
			List<Element> classes = (List) root.getChildren("class");
			for (Element element : classes) {
				String className = element.getAttributeValue("name");
				System.out.println(className + ":");
				if (((List) element.getChildren("student")).size() == 1) {
					Element sudent = element.getChild("student");
					String name = sudent.getChildText("name");
					String age = sudent.getChildText("age");
					String score = sudent.getChildText("score");
					System.out.println("My name is " + name + ",I'm " + age + " old! I'm in " + className + ",and I got " + score + " scores!");
				} else {
					for (Element student : (List<Element>) element.getChildren("student")) {
						String name = student.getChildText("name");
						String age = student.getChildText("age");
						String score = student.getChildText("score");
						System.out.println("My name is " + name + ",I'm " + age + " old! I'm in " + className + ",and I got " + score + " scores!");
					}
				}
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}